<template>
  <div class="app-container">
    <!-- <p>{{this.$route.params.row}}</p> -->
    <el-form :inline="true" :model="patientOv" class="demo-form-inline">
      <!-- <font size="4">患者医嘱管理</font>   <el-divider></el-divider> -->
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      <el-form-item label="患者姓名">
        <font style="color: #7b8d98;">{{patientOv.realName}}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font>
      </el-form-item>
      <el-form-item label="性别">
        <font style="color: #7b8d98;">{{patientOv.gender}}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font>
      </el-form-item>
      <el-form-item label="年龄">
        <font style="color: #7b8d98;">{{patientOv.age}}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font>
      </el-form-item><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      <el-form-item label="药物过敏史">
        <font style="color: #7b8d98;">{{patientRecord.drugAllergyHistory}}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font>
      </el-form-item>
      <el-form-item label="家族遗传病史">
        <font style="color: #7b8d98;">{{patientRecord.geneticDisease}}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font>
      </el-form-item>
    </el-form>
    <el-divider></el-divider>
    <!-- 查询框 -->
    <div class="filter-container">
      <el-input style="width: 200px;" v-model="pageParam.superSearchKeyWord" placeholder="关键字查询..." class="filter-item"
        @keyup.enter.native="handleFilter" @input="handleFilter" />
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreateDetail">
        添加病历详情
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="list" @sort-change="sortChange" fit highlight-current-row style="width: 100%;">

      <el-table-column class="filter-item" type="expand">
        <template slot-scope="{row}">
          <el-form label-position="left" inline class="demo-table-expand">



            <el-form-item label="病历详情">
              <span>{{ row.detail }}</span>
            </el-form-item>

            <el-form-item label="">
              <span></span>
            </el-form-item>

            <el-form-item label="创建时间">
              <span>{{ row.createTime.substring(0,10) }}</span>
            </el-form-item>

          </el-form>
        </template>
      </el-table-column>

      <!-- 表格字段 -->
      <!--      <el-table-column prop="detail" label="医嘱详情">
      </el-table-column> -->

      <el-table-column prop="id" label="序号" align="center" >
      </el-table-column>

      <el-table-column prop="createTime" label="创建时间" :formatter="formatTime">
      </el-table-column>


      <el-table-column label="操作" fit>
        <template slot-scope="{row,$index}">
          <el-button size="small" type="primary" @click="handleUpdate(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row,$index)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
      @pagination="getListByPage" />
    <!-- 弹窗组件 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="70px" style="width: 400px; margin-left:50px;">


        <!-- 弹窗 -->
        <el-form-item label="病历" prop="detail">
          <el-input type="textarea" height=200 v-model="temp.detail" />
        </el-form-item>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():(dialogStatus==='createDetail'?createDetail():updateData())">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="70px" style="width: 400px; margin-left:50px;">
        <!-- 弹窗 -->
        <el-form-item label="过敏史" prop="detail">
          <el-input height=200 v-model="patientRecord.drugAllergyHistory" />
        </el-form-item>
        <el-form-item label="遗传病史" prop="detail">
          <el-input height=200 v-model="patientRecord.geneticDisease" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="createData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">确认</el-button>
      </span>
    </el-dialog>




  </div>
</template>

<script>
  import {
    mapGetters,
    mapState
  } from 'vuex'
  //图片黏贴插件
  import '../../assets/js/image-paste.min.js'
  //quill富文本编辑器css
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  //quill富文本编辑器 组件倒入
  import {
    quillEditor
  } from 'vue-quill-editor'

  import {
    getToken
  } from '@/utils/auth'

  import {
    addMedicalRecord,
    updateMedicalRecord,
    getMedicalRecordOv,
    insertMedicalRecordDetail,
    updateMedicalRecordDetail,
    deleteMedicalRecordDetail
  } from '@/api/doctor/doctor.js'

  //倒入文件上传api
  import {
    uploadImage
  } from '@/api/file'

  //导入组件  记得声明组件
  import Pagination from '@/components/Pagination'

  export default {
    components: { //在这里声明组件
      Pagination,
      quillEditor
    },
    computed: {
      ...mapGetters({
        'userName': 'name',
        'roles': 'roles',
        'storeNickName': 'nickName'
      }),
      editor() {
        return this.$refs.myQuillEditor.quill
      }
    },
    data() {
      return {
        editorOption: {
          modules: {

            imagePaste: {
              addImageBlob: function(blob, callback) {
                var formData = new FormData()

                formData.append('image', blob)

                // console.log(blob, callback)

                // your upload function, get the uploaded image url, add then
                uploadImage(formData).then(res => {
                  console.log(res)
                  // let imageUrl =
                  //   'https://wnbucket.oss-cn-shanghai.aliyuncs.com/15930888655881592094766089.jpg'

                  callback(res.content)
                }).catch(err => {
                  console.log(err)
                })


              }
            }

          }
        },
        dialogImageUrl: '',
        dialogVisible: false,
        headerToken: {
          'Authorization': getToken()
        },
        imageUploadAction: process.env.VUE_APP_BASE_API + '/file/uploadImage',
        list: [], //列表数据
        total: 0,
        createTimeOrderOptions: [{
            label: '创建时间 升序',
            key: '+createTime',
            value: 'createTime asc'
          },
          {
            label: '创建时间 降序',
            key: 'createTime',
            value: 'createTime desc'
          }
        ],

        listQuery: { //分页 排序  查询参数
          pageNum: 1,
          pageSize: 5
        },
        fieldQuery: { // 按字段查询
          realName: ''
        },
        dialogFormVisible: false,
        dialogVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        dialogPvVisible: false,
        pvData: [],
        temp: {
          id: '',
          medicalRecordId: '',
          detail: '',
          createTime: '',
          updateUserId: '',
          updateTime: '',
          status: undefined,
          drugAllergyHistory: '',
          geneticDisease: ''
        },
        tempImageList: [

        ],
        newsCategoryList: [

        ],
        rules: {},
        pageParam: {
          pageNum: 1,
          pageSize: 5,
          model: {

          },
          orderParams: [],
          superSearchKeyWord: ''
        },
        roleList: [],
        patientOv: {},
        patientRecord: {
          id: '',
          patient_id: '',
          drugAllergyHistory: '',
          geneticDisease: '',
          medicalRecordId:''
        }
      }
    },
    created() {
      this.getListByPage()
    },
    methods: {
      sortChange(val) {
        // console.log("排序参数",val)
        let prop = val.prop
        let order = val.order === 'ascending' ? 'asc' : 'desc'
        let orderParam = prop + ' ' + order
        // console.log(orderParam)
        for (let i = 0; i < this.pageParam.orderParams.length; i++) {
          if (this.pageParam.orderParams[i].indexOf(prop) > -1) {
            this.pageParam.orderParams.splice(i, 1)
          }
        }
        this.pageParam.orderParams.push(orderParam)
        console.log(this.pageParam.orderParams)
        this.getListByPage()
      },
      getNewsCategoryList() {
        let pageNum = 1
        let pageSize = 1000
        let orderParams = []
        let model = {
          checkStatus: 1 //只查询 已经审核通过的分类
        }
        let pageParam = {
          pageNum,
          pageSize,
          orderParams,
          model
        }

        //   searchSomeNewscategoryByPage(pageParam).then(res => {
        //     // console.log(res)
        //     this.newsCategoryList = res.content.list
        //   }).catch(err => {
        //     console.log(err)
        //   })
      },
      getTempImageList() {
        //清空文件列表
        this.tempImageList = []

        let tempPageParam = this.pageParam
        tempPageParam.model = {
          productId: this.temp.id
        }
        tempPageParam.pageSize = 1000
        searchSomeProductimageByPage(tempPageParam).then(res => {
          // console.log(res)
          let resList = res.content.list
          let tempImageData = {
            name: '',
            url: '',
            key: ''
          }
          this.$refs.imagesUpload.clearFiles()
          for (let i = 0; i < resList.length; i++) {
            tempImageData.name = resList[i].imageUrl
            tempImageData.url = resList[i].imageUrl
            tempImageData.key = resList[i].imageUrl
            this.tempImageList.push(tempImageData)
          }

        }).catch(err => {
          console.log(err)
        })
      },
      getListByPage() {
        this.pageParam.pageNum = this.listQuery.pageNum
        this.pageParam.pageSize = this.listQuery.pageSize

        console.log(this.pageParam.orderParams)
        this.patientOv = this.$route.params.row
        let medicaData = {
          patientOv: this.patientOv,
          pageParam: this.pageParam
        }
        getMedicalRecordOv(this.patientOv).then(res => {
          // console.log(res)
          this.list = res.content.list
          this.total = res.content.total
          this.patientRecord.id = res.content.id
          this.patientRecord.drugAllergyHistory = res.content.drugAllergyHistory
          this.patientRecord.geneticDisease = res.content.geneticDisease
          this.patientRecord.medicalRecordId = res.content.id

        }).catch(err => {
          // this.$router.push({
          //     path: 'patientDetail'
          //   }),
          console.log(err)
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getListByPage()
      },
      handleCreate() {
        this.tempImageList = []
        // this.$refs.imagesUpload.clearFiles()
        this.resetTemp()
        this.getNewsCategoryList()
        // console.log(this.userName)
        this.temp.createUserNickName = this.storeNickName
        this.dialogStatus = 'create'
        this.dialogVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleCreateDetail() {
        this.tempImageList = []
        // this.$refs.imagesUpload.clearFiles()
        this.resetTemp()
        this.getNewsCategoryList()
        // console.log(this.userName)
        this.temp.createUserNickName = this.storeNickName
        this.dialogStatus = 'createDetail'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleUpdate(row) {
        console.log('edit:' + row)
        this.temp = Object.assign({}, row) // copy obj
        this.temp.id = row.id
        this.dialogStatus = 'update'
        // this.getTempImageList() // 展示商品图片列表
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      formatTime(row, column) {
        const date = new Date(row[column.property])
        return date.getFullYear() + '年' +
          date.getMonth() + '月' +
          date.getDate() + '日 ' +
          date.getHours() + ':' +
          date.getMinutes()
      },
      handleDelete(row, index) {

        let temp = {
          id: row.id
        }

        deleteMedicalRecordDetail(temp).then(() => {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getListByPage()
        })

      },
      createData() {
        this.patientRecord.patientId = this.patientOv.id
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            addMedicalRecord(this.patientRecord).then(() => {
              this.dialogVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
              this.getListByPage()
            })
          }
        })
      },
      createDetail() {
        this.temp.medicalRecordId = this.patientRecord.id
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            insertMedicalRecordDetail(this.temp).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              })
              this.getListByPage()
            })
          }
        })
      },
      updateData() {
        this.temp.medicalRecordId = this.patientRecord.id
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            updateMedicalRecordDetail(this.temp).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              })
              this.getListByPage()
            })
          }
        })
      },
      resetTemp() {
        this.temp = {
          id: '',
          patientId: '',
          detail: '',
          createUserId: '',
          createTime: '',
          updateUserId: '',
          updateTime: '',
          status: undefined
        }
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);

        let imageUrl = file.response == undefined ? file.url.replace('blob:', '') : file.response.content
        // let imageUrl = ''
        let productImageData = {
          imageUrl: imageUrl
        }
        deleteSomeProductimageTrueByCondition(productImageData).then(() => {

        })

      },
      handlePictureCardPreview(file) {
        console.log(file, fileList);
        // this.dialogImageUrl = file.url;
        console.log(file.url)
        this.temp.productImages = file.url
        this.dialogVisible = true;
      },
      handleImageSuccess(res, file) {
        // console.log(res,file)
        // this.temp.headPic = URL.createObjectURL(file.raw);
        // this.temp.productImages = res.content

        let productImageData = {
          imageUrl: res.content,
          productId: this.temp.id
        }
        addOneProductimage(productImageData).then(() => {

        })
      },
      handleAvatarSuccess(res, file) {
        // console.log(res,file)
        // this.temp.headPic = URL.createObjectURL(file.raw);
        this.temp.newsImage = res.content
      },
      beforeAvatarUpload(file) {
        console.log(file)
        const fileName = file.name
        const isImage = /.(gif|jpg|jpeg|png|gif|jpg|png)$/.test(fileName);
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isImage) {
          this.$message.error('上传头像图片只能是 gif|jpg|jpeg|png|gif|jpg|png 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isImage && isLt2M;
      },
      onEditorBlur(quill) {
        // console.log('editor blur!', quill)
      },
      onEditorFocus(quill) {
        // console.log('editor focus!', quill)
      },
      onEditorReady(quill) {
        // console.log('editor ready!', quill)
      },
      onEditorChange({
        quill,
        html,
        text
      }) {
        // console.log('editor change!', quill, html, text)
        this.temp.description = html
      },
      categoryChange() {
        this.getListByPage()
      },
      updateCheckStatus(row) {
        // console.log('edit:' + row)
        let temp = Object.assign({}, row) // copy obj
        temp.checkStatus = temp.checkStatus == 1 ? 2 : 1
        updateNewsinfo(temp).then(() => {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: temp.checkStatus == 1 ? '撤销成功' : '发布成功',
            type: 'success',
            duration: 2000
          })
          this.getListByPage()
        })
      },
      confirmCheck(row) {
        let temp = Object.assign({}, row) // copy obj
        temp.checkStatus = temp.checkStatus == 0 ? 1 : 0
        updateNewsinfo(temp).then(() => {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: temp.checkStatus == 0 ? '审核成功' : '取消审核成功',
            type: 'success',
            duration: 2000
          })
          this.getListByPage()
        })
      }
    },
    mounted() {
      this.getNewsCategoryList()
    }




  }
</script>

<style>
  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
